import * as express from "express";
import axios from "axios";
import * as url from "url";
import path from "path";
import fs from "fs"
// @ts-ignore
import {timeStampToTime} from "../util/common.js";
// @ts-ignore
import fetchAllStockData from "../util/analysePage.js";


// import * as FormData from "form-data";
// @ts-ignore
import { default as FormData } from "form-data";

function assembleContent(content:any[]):any[]{
    const newContent = content.map(item=>{
        const date = timeStampToTime(new Date().valueOf(), "YMD")
        item.rsi = item[`rsi(rsi1值)[${date}]`];
        item.买入信号 = item[`买入信号inter[${date}]`];
        item.技术形态 = item[`技术形态[${date}]`];
       return item;
    });
    return newContent;
}

function readFileAsJson(){
    const time = timeStampToTime(new Date().valueOf(), "YMD")
    const filePath = path.join(__dirname, `../data/${time}.json`)
    const hasFile = fs.existsSync(filePath)
    if(hasFile){
        const content = fs.readFileSync(filePath,"utf-8")
        const bodyMsg = assembleContent(JSON.parse(content));
        return bodyMsg
    }else{
        return {}
    }

}
export const register = (app: express.Application) => {
    app.get(`/api/search`, async (req: any, res) => {
        const tryFileData = readFileAsJson();
        if(Object.keys(tryFileData).length){
            const resBody = {
                serviceStatus: 2000,
                data:tryFileData,
            }
            return res.json(resBody)
        }

        // 远程获取
        const {query} = url.parse(req.url, true);
        const data = new FormData();
        data.append("question", "" + query.searchStr);
        data.append("perpage", "" + query.pageSize);
        data.append("page", "" + query.pageNum);
        data.append("source", "" + query.source);
        data.append("version", "" + query.version);

        const wenCaiUrl: string = "http://www.iwencai.com/unifiedwap/unified-wap/v2/result/get-robot-data";
        const config = {
            method: 'post',
            url: wenCaiUrl,
            headers: {
                'Cookie': `v=${query.hexinV};`,
                ...data.getHeaders()
            },
            data
        };

        // @ts-ignore
        axios(config)
            .then(async (response) => {
                const responseBody = response.data;
                if (responseBody.status_code === 0) {
                    const responseMsg = responseBody.data.answer[0].txt[0].content.components[0].data;
                    await fetchAllStockData(responseMsg.datas);
                    const readFileData = readFileAsJson();
                    if(Object.keys(readFileData).length){
                        const resBody = {
                            serviceStatus: 2000,
                            data:readFileData,
                        }
                        return res.json(resBody)
                    }else{
                        const resBody = {
                            serviceStatus: 2000,
                            data:{"message":"文件读取异常！"},
                        }
                        return res.json(resBody)
                    }
                } else {
                    const resBody = {
                        serviceStatus: 2001,
                        data: responseBody,
                    }
                    return res.json(resBody)
                }
            })
            .catch((error)=> {
                const resBody = {
                    serviceStatus: 4000,
                    data:error,
                }
                return res.json(resBody);

            });
    })

    app.get(`/api/search/result`, (req:any, res)=>{
        const resBody = {
            serviceStatus:"2000",
            serviceData:[
                {
                    id:1,
                    title:"条数1"
                },
                {
                    id:2,
                    title:"条数2"
                }
            ]
        }
        return res.json(resBody);
    })
}
